import React, {Fragment, PureComponent} from 'react';
import {connect} from 'dva';
import {Button, Card, Col, Divider, Dropdown, Form, Icon, Input, Menu, Modal, Row,} from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import TableList from '@/components/TableList';
import {ruleP} from '@/utils/rule'
import styles from '../search.less';

const {TextArea} = Input;
const FormItem = Form.Item;
const formLayout = {
  labelCol: {span: 6},
  wrapperCol: {span: 18},
};
const CreateForm = Form.create()(props => {
  const {
    modalVisible,
    form,
    addDataFn,
    updateFn,
    handleModalVisible,
    text,
  } = props;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      if (text) {
        updateFn(fieldsValue, text)
      } else {
        addDataFn(fieldsValue);
      }
    });
  };
  return (
    <Modal
      destroyOnClose
      width={640}
      title={text ? '编辑黑名单' : '新增黑名单'}
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible()}
      maskClosable={false}
    >
      <FormItem {...formLayout} label="IP开始">
        {form.getFieldDecorator('ipStart', {
          rules: [{required: true, message: 'IP不能为空'},
            {pattern: new RegExp(ruleP(3)[0], 'g'), message: ruleP(3)[1]}],
          initialValue: text && text.ipStart || ''
        })(<Input placeholder="请输入"/>)}
      </FormItem>

      <FormItem {...formLayout} label="IP结束">
        {form.getFieldDecorator('ipEnd', {
          rules: [{required: true, message: 'IP不能为空'},
            {pattern: new RegExp(ruleP(3)[0], 'g'), message: ruleP(3)[1]}],
          initialValue: text && text.ipEnd || ''
        })(
          <Input placeholder="请输入"/>
        )}
      </FormItem>
      <FormItem {...formLayout} label="MAC地址">
        {form.getFieldDecorator('macAddr', {
          rules: [{pattern: new RegExp(ruleP(8)[0], 'g'), message: ruleP(8)[1]}],
          initialValue: text && text.macAddr || ''
        })(
          <Input placeholder="请输入"/>
        )}
      </FormItem>
      <FormItem {...formLayout} label="备注">
        {form.getFieldDecorator('remark', {
          initialValue: text && text.remark || '',
          rules: [{max: 140, message: "字符长度不能超过140"}],
        })(
          <TextArea
            style={{minHeight: 32}}
            placeholder="请输入"
            rows={3}
          />)}
      </FormItem>
    </Modal>
  );
});

@Form.create()

/* eslint react/no-multi-comp:0 */
@connect(({blackList, loading}) => ({
  blackList,
  loading: loading.models.blackList,
}))
@Form.create()
class blackList extends PureComponent {
  state = {
    modalVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {},
    text: {},
    uploading: false,
  };

  columns = [
    {
      title: 'IP开始',
      dataIndex: 'ipStart',
    },

    {
      title: 'IP结束',
      dataIndex: 'ipEnd',
    },
    {
      title: 'MAC地址',
      dataIndex: 'macAddr',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
    },

    {
      title: '操作',
      render: (text, record) => (
        <Fragment>
          <a onClick={() => this.handleDetailModalVisible(true, record)}>详情</a>
          <Divider type="vertical"/>
          <Dropdown
            overlay={
              <Menu>
                <Menu.Item onClick={() => this.handleModalVisible(true, record)}>编辑</Menu.Item>
                <Menu.Item onClick={() => this.deleteData(text.id)}>删除</Menu.Item>
              </Menu>
            }
          >
            <a>更多 <Icon type="down"/></a>
          </Dropdown>
        </Fragment>
      ),
    },
  ];

  componentDidMount() {
    this.pageList();//列表查询
  }

  // 分页查询列表
  pageList(res, pageSize = 10, pageNum = 0) {
    const {dispatch} = this.props;
    const values = {
      macAddr: res && res.macAddr,
      pageSize: pageSize,
      pageNum: pageNum,
    };
    dispatch({
      type: 'blackList/queryList',
      payload: values,
      callback: (obj) => {
        if (obj.result == "ok" && res.userName) {

        }
      },
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const {formValues} = this.state;
    // 分页请求
    this.pageList(formValues, pagination.pageSize, pagination.current - 1);
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };


  deleteData = (id) => {
    Modal.confirm({
      title: '删除',
      content: '您确定要删除以下数据吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => this.handleThisRowDelete(id),
    });
  };
  batchDelete = (rows = []) => {
    const ids = rows.map((item) => {
      return item.id;
    }).join(",");
    this.deleteData(ids); //批量删除
  };
  handleThisRowDelete = (id) => {
    const {dispatch} = this.props;
    dispatch({
      type: 'blackList/remove',
      payload: {id},
      callback: (res) => {
        if (res.result == "ok") {
          this.setState({
            selectedRows: [],
          });
          Modal.success({title: res.msg});
          this.pageList();
        } else {
          Modal.error({title: '操作失败', content: res.msg});
        }
      },
    });
  }

  //查询
  handleSearch = e => {
    e.preventDefault();
    const {dispatch, form} = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };
      this.setState({
        formValues: values,
      });
      this.pageList(values);//列表查询
    });
  };


  handleModalVisible = (flag, text) => {
    this.setState({
      modalVisible: !!flag,
      text,
    });
  };

  handleDetailModalVisible = (flag, text) => {
    this.setState({
      detailModalVisible: !!flag,
      text,
    });
  };

  // 更新接口
  updateFn = (fields, text) => {
    const {dispatch} = this.props;
    const params = {
      ipStart: fields.ipStart,
      ipEnd: fields.ipEnd,
      macAddr: fields.macAddr,
      remark: fields.remark,
      id: text.id,
    }
    dispatch({
      type: 'blackList/update',
      payload: params,
      callback: (res) => {
        if (res.result == "ok") {
          Modal.success({title: res.msg});
          this.pageList();
        } else {
          Modal.error({title: '操作失败', content: res.msg});
        }
      },
    });
    this.handleModalVisible();
  };

  // 增加接口
  addDataFn = (fields) => {
    const {dispatch} = this.props;
    const mask = "255.255.255.0";
    // if(!this.isIpInOneNetMask( fields.ipStart,fields.ipEnd,mask)){
    //   Modal.error({title: '操作失败', content: "ip不在同一网段"});
    //   return
    // }


    const params = {
      ipStart: fields.ipStart,
      ipEnd: fields.ipEnd,
      macAddr: fields.macAddr,
      remark: fields.remark,
    }
    dispatch({
      type: 'blackList/add',
      payload: params,
      callback: (res) => {
        if (res.result == "ok") {
          Modal.success({title: res.msg});
          this.pageList();
        } else {
          Modal.error({title: '操作失败', content: res.msg});
        }
      },
    });
    this.handleModalVisible();
  };

  isIpInOneNetMask = (addr1, addr2,mask) => {
    if(!addr1 || !addr2 || !mask){
      return false;
    }
    var res1 = [], res2 = [];

    addr1 = addr1.split(".");
    addr2 = addr2.split(".");
    let o="00000000"
    for(var i = 0,ilen = addr1.length; i < ilen ; i += 1){
      let num1 = parseInt(addr1[i]).toString("2")
      if(num1.length!=8){
        let site=8-num1.length
        num1 = o.slice(0,site)+num1
      }
      let num2 = parseInt(addr2[i]).toString("2")
      if(num2.length!=8){
        let site=8-num2.length
        num2 = o.slice(0,site)+num2
      }
      res1.push(num1);
      res2.push(num2);
    }
    if(res1.join("").slice(0,parseInt(mask)) == res2.join("").slice(0,parseInt(mask))){
      return true;
    }else{
      return false;
    }

  }


  renderSimpleForm() {
    const {
      form: {getFieldDecorator},
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{md: 8, lg: 24, xl: 48}}>
          {/*<Col md={8} sm={24}>*/}
          {/*<FormItem label="IP开始">*/}
          {/*{getFieldDecorator('ipStart')(<Input placeholder=""/>)}*/}
          {/*</FormItem>*/}
          {/*</Col>*/}

          {/*<Col md={8} sm={24}>*/}
          {/*<FormItem label="IP结束">*/}
          {/*{getFieldDecorator('ipEnd')(<Input placeholder=""/>)}*/}
          {/*</FormItem>*/}
          {/*</Col>*/}
          <Col md={8} sm={24}>
            <FormItem label="MAC地址">
              {getFieldDecorator('macAddr')(<Input placeholder=""/>)}
            </FormItem>
          </Col>

          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    return this.renderSimpleForm();
  }

  render() {
    const {
      blackList: {data},
      loading,
    } = this.props;

    const {selectedRows, modalVisible, updateModalVisible, editFormValues, detailModalVisible, text} = this.state;
    const parentMethods = {
      addDataFn: this.addDataFn,
      updateFn: this.updateFn,
      handleModalVisible: this.handleModalVisible,
    };
    const detailsMethods = {
      handleDetailModalVisible: this.handleDetailModalVisible,
    };

    return (
      <PageHeaderWrapper title="黑名单">
        <Card bordered={false}>
          <CreateForm {...parentMethods} modalVisible={modalVisible} text={text}/>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <div className={styles.tableListOperator}>
              <Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true)}>
                新增
              </Button>
              {selectedRows.length > 0 && (
                <span>
                  <Button onClick={() => this.batchDelete(selectedRows)}>批量删除</Button>
                </span>
              )}
            </div>
            <TableList
              selectedRows={selectedRows}
              loading={loading}
              data={data}
              columns={this.columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
              rowKey={record => record.id}
            />
          </div>
          {detailModalVisible ?
            <Details {...detailsMethods} detailModalVisible={detailModalVisible} text={text}/> : null}
        </Card>
      </PageHeaderWrapper>
    );
  }
}

//查看详情弹窗
class Details extends PureComponent {
  constructor(props) {
    super(props);
  }

  render() {
    const {detailModalVisible, handleDetailModalVisible, text} = this.props;
    return (
      <Modal
        destroyOnClose
        width={800}
        title="查看详情"
        visible={detailModalVisible}
        onCancel={() => handleDetailModalVisible(false)}
        footer={[
          <Button key="back" type="primary" onClick={() => handleDetailModalVisible()}>返回</Button>
        ]}
        className={styles.viewMore}
      >
        <Row>
          <Col md={12}>
            <FormItem {...formLayout} label="IP开始">
              {text.ipStart}
            </FormItem>
          </Col>
          <Col md={12}>
            <FormItem {...formLayout} label="IP结束">
              {text.ipEnd}
            </FormItem>
          </Col>
          <Col md={12}>
            <FormItem {...formLayout} label="MAC地址">
              {text.macAddr}
            </FormItem>
          </Col>
          <Col md={12}>
            <FormItem {...formLayout} label="创建时间">
              {text.createTime}
            </FormItem>
          </Col>
          <Col md={24}>
            <FormItem labelCol={{span: 3}} wrapperCol={{span: 21}} label="备注">
              {text.remark}
            </FormItem>
          </Col>
        </Row>
      </Modal>
    );
  }
}

export default blackList;
